import { message } from "antd";
import { fetchData } from "../utils/fetchCollections/fetch";
import { sendFlip } from "../utils/fetchCollections/Flip/sendFlip";

export type flipCardData = {
  xoxId: number;
  xoxNickname: string;
  cards: {
    answerId: string;
    cost: number;
    answerType: number;
    answerTime: string;
    qtime: string;
    type: number
  }[]
}

export type DataSourcePageParams = {
  pageSize?: number;
  pageNum?: number;
  xoxId?: number;
  startTimeMs?: number;
  endTimeMs?: number;
  type?: number;
  status?: number;
  answerType?: number;
  keyword?: string;
}

export type FlipKeyInfoForSend = {
  memberId: string;
  content: string;
  type: number;
  cost: string;
  answerType: number;
}
export class FlipService {
  private static groupDataById(allUserData: any[]): Record<string, flipCardData> {
    const groupData: Record<string, flipCardData> = {};

    allUserData.forEach((item) => {
      const xoxId = item?.baseUserInfo?.userId;
      const cardInfo = {
        answerId: item?.answerId,
        cost: item?.cost,
        answerType: item?.answerType,
        answerTime: item?.answerTime,
        qtime: item?.qtime,
        type: item?.type
      }
      if (xoxId in groupData) {
        groupData[xoxId].cards.push(cardInfo);
      } else {
        groupData[xoxId] = {
          xoxId,
          xoxNickname: item?.baseUserInfo?.nickname,
          cards: [cardInfo]
        }
      }
    });

    return groupData;
  }
  static async getAllFlips(token: string, userId: string) {
    let allUserData: any[] = [];
    let shouldLogout = false
    let beginLimit = 0;
    let responseSize = 20;
    let stopT = 0;
    let groupNum = 40;
    let dashboardInfo: any = {};
    try {
      while (responseSize > 0) {
         const response = await fetchData(
           "https://pocketapi.48.cn/idolanswer/api/idolanswer/v1/user/question/list",
           {
             status: 0,
             beginLimit: beginLimit,
             memberId: "",
             limit: 20,
           },
           token
         );
         let sleepTime = 10;
         if (beginLimit - stopT * groupNum * responseSize > 100) {
           sleepTime = 60000;
           stopT += 1;
         }
   
         if (response.status === 200) {
           const userData = response.content;
           allUserData = allUserData.concat(userData);
           responseSize = userData.length;
           beginLimit += 20;
           await new Promise((resolve) => setTimeout(resolve, sleepTime)); // 添加1秒延迟
         }
         else if (response.status === 401004) {
           // 登录过期，重新登录
           message.error('登录过期，请重新登录');
           shouldLogout =  true
           return {allUserData, dashboardInfo, shouldLogout};
          // navigate('/login');
          } else {
           alert(`获取翻牌数据失败: ${response.message}`);
           break;
         }
      }
      console.log("allUserData:", allUserData);

      // 然后要统计一下 dashboard
      if (allUserData.length > 0) {
         dashboardInfo = {
          totalFlipCount: allUserData.length,
          runningCount: 0,
          returnedCount: 0,
          costTotal: 0
         }
         allUserData.forEach((card) => {
            if (card?.status === 3) {
               // 已退回
               dashboardInfo.returnedCount += 1;
            } else if (card?.status === 1) {
               // 进行中
               dashboardInfo.runningCount += 1;
            } else if (card?.status === 2) {
               // 已处理
               dashboardInfo.costTotal += card?.cost;
            }
         })
         const groupedData = this.groupDataById(allUserData);
         await chrome.storage.local.set({ 'groupedDataById': groupedData });
         const oriAllUserData = await chrome.storage.local.get('allUserData');
         let newAllUserData = {...oriAllUserData}
         newAllUserData[userId] = allUserData;
         await chrome.storage.local.set({ 'allUserData': newAllUserData });
      } else {
         message.warning('没有翻牌记录')
      }
    } catch (error) {
      console.error(error);
      return {};
    }

    return {allUserData, dashboardInfo, shouldLogout};
  }
  // static async getNewMessage(token: string) {
    
  // }

  static async getDataSourcePage(searchParams: DataSourcePageParams, userId: string) {
    const { pageSize = 20, pageNum = 1, xoxId, startTimeMs, endTimeMs, type, status, answerType, keyword } = searchParams;
    const response = {
      pageSize,
      pageNum,
      data: [],
      total: 0
    }
    // 1、加载数据源
    const { allUserData: fullAllUserData } = await chrome.storage.local.get('allUserData');
    const allUserData = fullAllUserData?.[userId];
    console.log("fullAllUserData", fullAllUserData, "allUserData:", allUserData)
    if (allUserData?.length === 0 || !allUserData) {
      return response;
    }
    // 2、过滤数据
    const filteredData = allUserData.filter((item: any) => {
      if (xoxId && `${item?.baseUserInfo?.userId}` !== `${xoxId}`) {
        return false;
      }
      if (startTimeMs && Number(item?.qtime || Infinity) < Number(startTimeMs)) {
        return false;
      }
      if (endTimeMs && Number(item?.qtime || 0) > Number(endTimeMs)) {
        return false;
      }
      if (type && `${item?.type}` !== `${type}`) {
        return false;
      }
      if (status && `${item?.status}` !== `${status}`) {
        return false;
      }
      if (answerType && `${item?.answerType}` !== `${answerType}`) {
        return false;
      }
      if (keyword && (!item?.answerContent?.includes(keyword) && !item?.content?.includes(keyword))) {
        return false;
      }
      return true;
    });

    // 2、加载分页数据
    // const pageData = filteredData.slice((pageNum - 1) * pageSize, pageNum * pageSize);
    // response.data = pageData;
    response.data = filteredData;
    response.total = filteredData?.length || 0;
    console.log("filteredData:", filteredData)
    return response;
  }
  
  static async sendFlip(info: FlipKeyInfoForSend, token: string) {
    const res = await sendFlip(token, info);
    if (res) {
      return res;
    } else {
      return false;
    }
  }
}
